package com.shengdong.water.code.adapter

import android.view.View
import com.shengdong.water.R
import com.shengdong.water.code.base.BaseRecyclerAdapter
import com.shengdong.water.code.ext.loadRoundedImage
import com.shengdong.water.databinding.ItemMonitorPicBinding
import kotlin.text.compareTo

class ImagePickerAdapter: BaseRecyclerAdapter<String, ItemMonitorPicBinding>() {

    companion object {
        private const val MAX_IMAGE_COUNT = 9
    }

    init {
        // 初始化时添加一个空项来显示添加按钮
        setItems(listOf(String()))
    }
    override fun getLayoutId() = R.layout.item_monitor_pic


private var onAddClickListener: (() -> Unit)? = null
    override fun bindData(binding: ItemMonitorPicBinding, item: String, position: Int) {
//        binding.item = item
        // 可以在这里添加额外的绑定逻辑
        if (position == itemCount - 1 && itemCount <= MAX_IMAGE_COUNT) {
            // 显示添加按钮
            binding.itemAdd.visibility = if (itemCount < MAX_IMAGE_COUNT) View.VISIBLE else View.GONE
            binding.flPic.visibility = View.GONE

            binding.itemAdd.setOnClickListener {
                onAddClickListener?.invoke()
            }
        }else {
            binding.itemAdd.visibility = View.GONE
            binding.flPic.visibility = View.VISIBLE
            binding.itemPic.loadRoundedImage(item, radius = 5f)

            // 删除按钮点击事件
            binding.itemDel.setOnClickListener {
                val currentList = getItems().toMutableList()
                currentList.removeAt(position)
                setItems(currentList)
            }
        }

        binding.executePendingBindings()
    }

    fun setOnAddClickListener(listener: () -> Unit) {
        this.onAddClickListener = listener
    }


    // 在 ImagePickerAdapter 中添加一个方法来更新数据
    fun updateImages(newImage: String) {
        val currentList = getItems().toMutableList()
        // 移除添加按钮
        if (currentList.isNotEmpty()) {
            currentList.removeAt(currentList.lastIndex)
        }
        currentList.add(0, newImage)
        // 如果未达到最大数量限制，添加回添加按钮
        if (currentList.size < MAX_IMAGE_COUNT) {
            currentList.add("")
        }
        setItems(currentList)
    }


}